package ru.ya.kolemik.servcmd.filters;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class StaticFilter extends AbstractFilter {
    
    private String [] staticResources = new String [] {"/IMG/"};
    
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        log.debug("StaticFilter - set character encoding.");
        HttpServletRequest httpRequest = ((HttpServletRequest)request);
        String uri = (String) httpRequest.getAttribute("javax.servlet.include.request_uri");
        if (uri == null) {
            uri = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        } else {
            uri = uri.substring(httpRequest.getContextPath().length());
        }
        log.debug("StaticFilter - URI: " + uri);
        
        if (uri != null) {
            for (String prefix : staticResources) {
                if (uri.startsWith(prefix)) {
                    log.debug("Статический ресурс");
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        httpRequest.getRequestDispatcher("/cont" + uri).include(request, response);
    }
    
}
